﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using GMap.NET;
using GMap.NET.MapProviders;
using Common;
using Model;
using GMap.NET.WindowsForms;
using System.Linq;

namespace TaxiDispatchClient
{
    public partial class NewsPushForm : DevExpress.XtraEditors.XtraForm
    {
        public NewsPushForm()
        {
            InitializeComponent();
        }
        //87
        private DataTable _dtTaxiList;
        private Thread t;
        private readonly GMapControl _gMap = new GMapControl();

        private bool isReceFirst = false;

        private Socket _sendtoTransferServer;

        public NewsPushForm(DataTable taxilist)
        {
            InitializeComponent();

            _dtTaxiList = taxilist.Copy();
            _dtTaxiList.Rows.Clear();
            foreach (DataRow row in taxilist.Rows)
            {
                int carType = int.Parse(row["车辆类型"].ToString());
                if (carType == ConstParameters.CarTypeOfTaxi)
                {
                    _dtTaxiList.Rows.Add(row.ItemArray);
                }
            }
           


           // _dtTaxiList = taxilist.Copy();
            gridControl_TaxiList.DataSource = _dtTaxiList;
            gridView1.GroupPanelText = "当前一共" + _dtTaxiList.Rows.Count + "辆出租车.    " + DateTime.Now;
            _gMap.MapProvider = GMapProviders.GoogleChinaMap;
            gridView1.FocusedRowHandle = -1;
        }




        private void simpleButton_SendToTaxi_Click(object sender, EventArgs e)
        {
            if (memoEdit_SendNews.Text.Trim()=="")
            {
                XtraMessageBox.Show("请填写推送内容！");
                return;
            }
            int count = gridView1.GetSelectedRows().Count();
            if (count==0)
            {
                XtraMessageBox.Show("请选择推送目标车辆，单击左边列表中的出租车即可选中该行车辆！");
                return;
            }
            if (XtraMessageBox.Show("当前公选中"+count+"辆出租车，确认向其推送该新闻？", 
                "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                btn_sendToTaxi.Enabled = false;
                try
                {
                    isReceFirst = false;
                    string transferServerIP = OperateConfig.GetClientTransferServerIp();
                    IPAddress ipAddress = IPAddress.Parse(transferServerIP);
                    _sendtoTransferServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPEndPoint address = new IPEndPoint(ipAddress, ConstParameters.TransferListenPort);
                    _sendtoTransferServer.NoDelay = true;
                    _sendtoTransferServer.Connect(address);
                }
                catch (Exception ex)
                {
                    btn_sendToTaxi.Enabled = true;
                    //btn_sendSMS.Enabled = true;
                    CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
                t = new Thread(SendMessageToTaxi);
                t.Start();
            }
        }


        private void SendMessageToTaxi()
        {
            try
            {

                Dictionary<string, byte[]> phoneNuber_sendData = new Dictionary<string, byte[]>();
                bool isSomeOneTaxiAnswer = false;
                 
                byte[] phoneNumberBytes = CommonRoutine.BcdStringToBytes("000000000000");

                int[] drsIndex = gridView1.GetSelectedRows();
                foreach (int index in drsIndex)
                {
                    DataRow dr = gridView1.GetDataRow(index);
               
                //for (int i = 0; i < gridView1.RowCount; i++)
                //{
                 //   DataRow dr = gridView1.GetDataRow(i);
                    if (dr["出租车状态"].ToString() == "空载")
                    {
                        string phoneNumber = dr["司机号码"].ToString();
                        string strCommand = memoEdit_SendNews.Text;
                        IPAddress localIp = ((IPEndPoint)(_sendtoTransferServer.LocalEndPoint)).Address;
                        List<byte> mBytes = new List<byte>();

                        mBytes.AddRange(BitConverter.GetBytes(ConstParameters.CmdSendNewsToTaxi).Reverse());
                        mBytes.AddRange(CommonRoutine.BcdStringToBytes(phoneNumber.PadLeft(12, '0')));

                        mBytes.AddRange(localIp.GetAddressBytes());
                        mBytes.Add(4);


                        string datestring = DateTime.Now.ToString("yyyyMMddHHmmss");

                        mBytes.AddRange(CommonRoutine.BcdStringToBytes(datestring));

                        mBytes.AddRange(Encoding.GetEncoding("GBK").GetBytes(strCommand));
                        byte[] messageBody = mBytes.ToArray();


                        byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdRetweetTaxiDispatchClient, false, false, messageBody.Length, phoneNumberBytes, new byte[2], 0, 0);
                        byte[] sendData = OperateAgreement.PackageSendData(messageHead, messageBody);
                        //Thread.Sleep(300);
                       // _sendtoTransferServer.Send(sendData);
                        _sendtoTransferServer.Send(sendData);
                   
                        phoneNuber_sendData.Add(phoneNumber, sendData);
                    }
                }

                List<byte> receBufferBb = new List<byte>();

                DateTime sendTime = DateTime.Now;
                List<string> phoneNumber_List = new List<string>();

                while (true)
                {
                    #region retrySend
                    DateTime now = DateTime.Now;
                    TimeSpan timeSpan = new TimeSpan(now.Ticks - sendTime.Ticks);
                    if (timeSpan.TotalSeconds > 15)
                    {
                        foreach (KeyValuePair<string, byte[]> keyValuePair in phoneNuber_sendData)
                        {
                            if (!phoneNumber_List.Contains(keyValuePair.Key))
                            {
                                _sendtoTransferServer.Send(keyValuePair.Value);
                            }
                        }
                        Thread.Sleep(1000);

                    }
                    #endregion

                    #region rece Data
                    try
                    {
                        byte[] receBuffer = new byte[100];
                        int receDataLength = _sendtoTransferServer.Receive(receBuffer);
                        Thread.Sleep(1);
                        byte[] temp = new byte[receDataLength];
                        Array.Copy(receBuffer, 0, temp, 0, temp.Length);
                        receBufferBb.AddRange(temp);
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                    }
                    #endregion
                    int receBufferBBindex = 0;
                    int sendflag = -1;
                    int endindex = 0;
                    List<byte> receByteList = new List<byte>();

                    foreach (byte b in receBufferBb)
                    {
                        receBufferBBindex++;
                        if (b == 0x7e) sendflag++;
                        if (sendflag >= 0)
                        {
                            if (sendflag == 0) { receByteList.Add(b); }
                            else if (sendflag == 1)
                            {
                                receByteList.Add(b);
                                byte[] receData = receByteList.ToArray();
                                receByteList.Clear();
                                sendflag = -1;
                                endindex = receBufferBBindex;
                                #region
                                byte[] realData = OperateAgreement.RestoreReceData(receData);
                                if (OperateAgreement.JudgeisCompleteData(realData))
                                {
                                    ushort messageId = OperateAgreement.GetMessageIdInMessageHead(realData);
                                    string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

                                    phoneNumber_List.Add(phoneNumber);

                                    if (messageId == ConstParameters.CmdSendNewsToTaxiReply)
                                    {
                                        BeginInvoke(new MethodInvoker(() =>
                                        {

                                            if (!isReceFirst)
                                            {
                                              XtraMessageBox.Show("发送成功！");
                                                isReceFirst = true;
                                            }
                                        
                                            btn_sendToTaxi.Enabled = true;
                                        }));
                                        
                                    }
                                }
                                #endregion
                            }
                        }
                    }
                    if (endindex > 0)
                    {
                        receBufferBb.RemoveRange(0, endindex);
                    }

                }            

                //  sendtoTransferServer.Close();
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
            }
        }
        private void CallForTaxiForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (t != null) t.Abort();
                _sendtoTransferServer.Shutdown(SocketShutdown.Both);
                _sendtoTransferServer.Close();
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
            }
        }

        private void btn_clearNews_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("确定清空文本框中的内容？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                memoEdit_SendNews.Text = "";
            }
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            string parameter;
            string parameterVaule = textEdit_condition.Text;
            if (radioGroup_SelectType.SelectedIndex == 0)
            {
                parameter = "出租车牌照";
            }
            else if (radioGroup_SelectType.SelectedIndex == 1)
            {
                parameter = "出租车车型";
            }
            else
            {
                if (textEdit_condition.Text.Trim() == "")//**********新加未测
                {
                    return;
                }
                parameter = "所属公司";
            }

            if (_dtTaxiList.Rows.Count == 0)
            {
                GetAllTaxiList();
            }


            _dtTaxiList.DefaultView.RowFilter = parameter + " like '%" + parameterVaule + "%'";
            gridControl_TaxiList.DataSource = _dtTaxiList.DefaultView;
            gridView1.GroupPanelText = "当前一共" + _dtTaxiList.DefaultView.Count + "辆出租车.    " + DateTime.Now;
        }

        private void GetAllTaxiList()
        {
            try
            {
                List<TaxiInfo> taxiInfos = MainForm.PositionService.GetAllTaxiInfos();

                _dtTaxiList.Clear();
                _dtTaxiList.DefaultView.RowFilter = "";
                foreach (TaxiInfo taxiInfo in taxiInfos)
                {
                    if (taxiInfo.TaxiState == 0)
                    {
                        DataRow dr = _dtTaxiList.NewRow();
                        dr["司机姓名"] = taxiInfo.DriverName;
                        dr["出租车牌照"] = taxiInfo.TaxiNo;
                        dr["司机号码"] = taxiInfo.DriverPhoneNumber;
                        dr["出租车状态"] = OperateAgreement.GetTaxiState(taxiInfo.TaxiState);
                        dr["出租车车型"] = taxiInfo.TaxiType;
                        dr["经度"] = taxiInfo.Latitude;
                        dr["纬度"] = taxiInfo.Longitude;
                        dr["所属公司"] = taxiInfo.Remark;
                        dr["数据更新时间"] = taxiInfo.UpdateTime.ToString("HH:mm:ss");
                        dr["IP地址"] = taxiInfo.Ip;
                        dr["出租车ID"] = taxiInfo.Id;
                        _dtTaxiList.Rows.Add(dr);
                    }

                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
            }

        }

        private void btn_getall_Click(object sender, EventArgs e)
        {
            GetAllTaxiList();
            gridControl_TaxiList.DataSource = _dtTaxiList;
            gridView1.GroupPanelText = "当前一共" + _dtTaxiList.Rows.Count + "辆出租车.    " + DateTime.Now;
        }

        #region 窗体效果
        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;
            Cursor = Cursors.Arrow;
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Close();
        }


        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }
        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }

        #endregion



    }
}